<?php

namespace App\Providers;

use App\Admin\Form;
use App\Admin\Utils\Config;
use Illuminate\Support\ServiceProvider;
use Overtrue\LaravelWeChat\CacheBridge;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Config::load();
        $this->setWechatConfig();
        Form::registerBuiltinFields();
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('AdminConfig', function () {
            return new Config();
        });

        $this->packageConfigs();

        $this->registerDevPackages();

        $this->customBlade();
    }

    protected function packageConfigs()
    {
        // 设置Faker的地区,可用来生成中文的姓名,和中国的手机号码
        $this->app->bind('Faker\Generator', function () {
            return \Faker\Factory::create('zh_CN');
        });
    }

    protected function registerDevPackages()
    {
        if (config('app.debug')) {
            $this->app->register(\VIACreative\SudoSu\ServiceProvider::class);
        }
    }

    protected function customBlade()
    {
        \Blade::directive('ctx', function ($expression) {
            return '<?php if ($ctx = '."$expression): ?>";
        });

        \Blade::directive('endctx', function () {
            return "<?php endif; ?>";
        });
    }

    protected function setWechatConfig()
    {
        $name = 'official_account';
        $account = 'default';
        $config = [
            'app_id'  => config('admin.official_account_app_id'),
            'secret'  => config('admin.official_account_secret'),
            'token'   => config('admin.official_account_token'),
            'aes_key' => config('admin.official_account_aes_key'),

            // 'oauth' => config('wechat.official_account.default.oauth'),
        ];
        $class = 'EasyWeChat\OfficialAccount\Application';

        $this->app->singleton("wechat.{$name}.{$account}", function ($laravelApp) use ($name, $account, $config, $class) {
            $app = new $class(array_merge(config('wechat.defaults', []), $config));
            if (config('wechat.defaults.use_laravel_cache')) {
                $app['cache'] = new CacheBridge($laravelApp['cache.store']);
            }
            $app['request'] = $laravelApp['request'];

            return $app;
        });
    }
}
